﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Timers;
using Serie_Counter.DataLayer;
using Timer = System.Timers.Timer;

namespace Serie_Counter.BusinissLayer
{
    public class BL_FileMoving
    {
        private BL_Manager manager;
        private Timer timer;
        private IO_FileMoving fileMoving;

        /// <summary>
        /// set timer interval in minutes
        /// </summary>
        public int TimerInterval
        {
            set
            {
                if (value == 0)
                {
                    value = 30;
                }
                timer.Interval = value * 60000;
            }
        }

        public BL_FileMoving(int checkInterval, BL_Manager manager, bool start = true)
        {
            
            this.manager = manager;
            timer = new Timer();
            if (checkInterval == 0)
            {
                checkInterval = 15;
            }
            timer.Interval = (checkInterval * 60000);
            timer.Elapsed += new ElapsedEventHandler(timeElapsed);
            if (start) timer.Start();
        }

        public void start()
        {
            timer.Start();
        }

        public void pause()
        {
            timer.Stop();
        }

        private void timeElapsed(object sender, EventArgs e)
        {
            fileMoving = new IO_FileMoving(manager.getSettings().RootFolder);
            List<string[]> moveAbleSeries = manager.getMoveAbleSeries();

            foreach (string[] ableSeries in moveAbleSeries)
            {
                fileMoving.moveFiles(ableSeries[0], ableSeries[1]);
            }
        }

        /// <summary>
        /// check files independent of the timer (when Running a timer)
        /// </summary>
        public void checkFiles()
        {
            bool wasEnabled = timer.Enabled;
            if(timer.Enabled) timer.Stop();

            timeElapsed(new object(), null);

            if(wasEnabled) timer.Start();
        }

        /// <summary>
        /// check files once (ex. at startup)
        /// </summary>
        /// <param name="manager"></param>
        public static void checkFilesStatic(BL_Manager manager)
        {
            //todo: could go in a thread => locks on manager data like serie list
            IO_FileMoving fileMoving = new IO_FileMoving(manager.getSettings().RootFolder);
            List<string[]> moveAbleSeries = manager.getMoveAbleSeries();

            foreach (string[] ableSeries in moveAbleSeries)
            {
                fileMoving.moveFiles(ableSeries[0], ableSeries[1]);
            }
        }

    }
}
